package service

import (
	"github.com/gofiber/fiber/v2"
	"guns-excel/internal/app/model"
	"guns-excel/internal/app/repository"
	"guns-excel/internal/pkg/database"
	"guns-excel/internal/pkg/util"
	"time"
)

func AddModel(ctx *fiber.Ctx, model *model.Model) error {
	model.Id = util.GetId()
	nowDate := time.Now()
	model.CreatedOn = &nowDate
	return repository.AddModel(ctx, model, database.MysqlDB)
}
func GetModelByModelId(ctx *fiber.Ctx, modelId string) (*model.Model, error) {
	return repository.GetModelByModelId(ctx, modelId, database.MysqlDB)
}

func GetModelTree(ctx *fiber.Ctx) ([]*model.Model, error) {
	listModel, err := repository.GetListModel(ctx, database.MysqlDB)
	if err != nil {
		return nil, err
	}
	treeModel := make([]*model.Model, 0)
	for _, m := range listModel {
		if m.ParentId != "0" {
			continue
		}
		// 先把所有父模型加入treeModel中
		treeModel = append(treeModel, coverTree(listModel, m))
	}
	return treeModel, nil
}

func coverTree(list []*model.Model, m *model.Model) *model.Model {
	// 存放找到的节点
	min := make([]*model.Model, 0)
	for _, ls := range list {
		if m.Id != ls.ParentId {
			continue
		}
		mo := model.Model{}
		mo.Id = ls.Id
		mo.ParentId = ls.ParentId
		mo.ModelName = ls.ModelName
		mo.TableSchema = ls.TableSchema
		mo.TableName = ls.TableName
		mo.Sort = ls.Sort
		mo.CreatedOn = ls.CreatedOn
		mo.CreatedBy = ls.CreatedBy
		mo.ModifiedOn = ls.ModifiedOn
		mo.ModifiedBy = ls.ModifiedBy
		mo.DeletedOn = ls.DeletedOn
		mo.DeletedBy = ls.DeletedBy
		mo.IsDel = ls.IsDel
		mo.Children = []*model.Model{}
		ms := coverTree(list, &mo)
		min = append(min, ms)
	}
	m.Children = min
	return m
}
